package com.app.buss.mvp.presenter;


import android.util.Log;

import com.google.gson.GsonBuilder;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableObserver;
import retrofit2.adapter.rxjava2.HttpException;



/**
 * api请求通用回调
 */
public abstract class ApiCallback<M> extends DisposableObserver<M> {

    public abstract void onSuccess(M model);

    public abstract void onFailure(String msg, int code);

    public abstract void onFinish();

    protected CompositeDisposable mDisposable;
    protected void unSubscribe() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }

    protected void addDisposable(Disposable subscription) {
        if (mDisposable == null) {
            mDisposable = new CompositeDisposable();
        }
        mDisposable.add(subscription);
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            //httpException.response().errorBody().string()
            int code = httpException.code();
            String msg = httpException.getMessage();
            if (code == 504) {
                msg = "网络不给力";
            }
            if (code == 502 || code == 404) {
                msg = "服务器异常，请稍后再试";
            }
            onFailure(msg,code);
        } else {
            onFailure(e.getMessage(),500);
        }
        onFinish();
    }

    @Override
    public void onNext(M model) {
        Log.e("返回数据:",new GsonBuilder().disableHtmlEscaping().create().toJson(model));
        onSuccess(model);
    }

    @Override
    public void onComplete() {
        onFinish();
        unSubscribe();
    }
}
